import {Component} from '@angular/core';
import {IonicPage, LoadingController, ModalController, NavController, NavParams, ToastController} from 'ionic-angular';
import {TranslateService} from "@ngx-translate/core";
import {Api} from "../../providers/api/api"
import {Browser} from "../../providers/browser/browser"

/**
 * Generated class for the RankPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-rank',
  templateUrl: 'rank.html',
})
export class RankPage {

  pages: Array<any> = [];
  private networkErrorString: string;
  private params: any = {'page': 0, 'size': 20, 'kind': 0};

  constructor(public translateService: TranslateService,
              public navCtrl: NavController,
              public navParams: NavParams,
              public api: Api,
              public toastCtrl: ToastController,
              public loadingCtrl: LoadingController,
              public modalController: ModalController,
              public browser: Browser) {
    this.loadingCtrl.create({
      content: "数据加载中",
      duration: 500
    }).present();
    this.getPages();
    this.translateService.get('NETWORK_ERROR').subscribe((value) => {
      this.networkErrorString = value;
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RankPage');
  }

  doRefresh(refresher) {
    console.log('Begin async operation', refresher);
    this.pages = [];
    this.params.page = 0;
    this.getPages();
    setTimeout(() => {
      refresher.complete();
    }, 500);
  }

  doInfinite(infiniteScroll) {
    this.params.page = this.params.page + 1;
    this.getPages();
    setTimeout(() => {
      infiniteScroll.complete();
    }, 1000);
  }

  getPages() {
    let reqParam = "?page=" + this.params.page + "&size=" + this.params.size + "&sort=hits,desc";
    let seq = this.api.get('plans' + reqParam).share();
    seq.subscribe((res: any) => {
      // If the API returned a successful response, mark the user as logged in
      if (res) {
        this.pages = this.pages.concat(res);
      } else {
        this.showToast().present();
      }
    }, err => {
      this.showToast().present();
      console.error('ERROR', err);
    });
    return seq;
  }

  openSearch() {
    let modal = this.modalController.create("SearchPage");
    modal.present();
  }

  showToast() {
    return this.toastCtrl.create({
      message: this.networkErrorString,
      duration: 1000,
      position: 'top'
    });
  }

  openDetail(planDetail) {
    this.navCtrl.push('PlanDetailPage', planDetail);
  }
}
